//
//  BIZHomePageViewController.m
//  jiedabao
//
//  Created by 小龙 on 2017/3/15.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZHomePageViewController.h"
#import "BIZCustomSearchBar.h"
// VC
#import "BIZConsultorListViewController.h"
#import "BIZBusinessPremisesListVC.h"
#import "BIZDWPlayerViewController.h"
#import "BIZLoginViewController.h"
#import "BIZPlayForPCVC.h"
#import "BIZBusinessPremisesDetailVC.h"
#import "BIZOfflineConsultRecordsVC.h"
#import "BIZContractVC.h"
#import "BIZRemoteNotificationWebVC.h"
#import "BIZConsultViewController.h"
#import "BIZLivePlayBackVC.h"
#import "BIZLiveHistoryAnswerVC.h"
#import "BIZHotTopicsHomeVC.h"

// cell
#import "BIZHomeLiveStreamingCell.h"
#import "BIZBussinessPremissCell.h"

#import "BIZCCLiveRequestTool.h"
// model
#import "BIZLiveRoomDetailInfoModel.h"
#import "BIZOfficeModel.h"
#import "BIZCycleScrollViewImagesModel.h"

#import "BIZFinanceTaxCircleVC.h"
#import "BIZArticleListCell.h"
#import "BIZArticleDetailVC.h"
#import "BIZArticleModel.h"

#import "BIZSynchronousTutorialListVC.h"
#import "BIZSynchronousTutorialHomeCell.h"
#import "BIZSynchronousTutorialModel.h"
#import "BIZConsultEditViewController.h"
#import "BIZSynchronousTutorialVideoDetailVC.h"
#import "BIZSynchronousTutorialWordDetailVC.h"
#import "BIZHomeSectionHeaderView.h"
#import "BIZMoviePlaySitcomListDataModel.h"
#import "BIZSynchronousTutorialModel.h"

#import "BIZHotTopicDetailVC.h"

typedef void (^SDScrollViewClickItemOperationBlock)(NSInteger currentIndex);

@interface BIZHomePageViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate,SDCycleScrollViewDelegate>

@property (weak, nonatomic) IBOutlet SDCycleScrollView *cycleScrollView;


/** strong属性注释 */
@property (nonatomic, strong) NSArray *localCycleImageArr;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** SearchBar */
@property (nonatomic, strong) BIZCustomSearchBar *searchBar;

//@property (weak, nonatomic) IBOutlet UIButton *one2OneConsultBtn;
//
//@property (weak, nonatomic) IBOutlet UIView *consultRedView;
//@property (weak, nonatomic) IBOutlet UIView *contractRedView;
//@property (weak, nonatomic) IBOutlet UIView *lineDownRedView;
@property (weak, nonatomic) IBOutlet UIView *o2oRedView;
@property (weak, nonatomic) IBOutlet UIView *repaidRedView;

/** 事务所列表 */
//@property (nonatomic, strong) NSMutableArray *officeModelArr;

/** 轮播图列表 */
@property (nonatomic, strong) NSMutableArray *cycleScrollViewImgesList;

/** 轮播图模型列表 */
@property (nonatomic, strong) BIZCycleScrollViewImagesModel *cycleScrollViewImgesModel;
/** 直播预告图模型列表 */
@property (nonatomic, strong) BIZCycleScrollViewImagesModel *cclivePredictionImgesModel;

/** 直播间详情模型 */
@property (nonatomic, strong) BIZLiveRoomDetailInfoDataModel *liveRoomInfoDataM;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *o2oRightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *repaidLeftLayout;

@property (weak, nonatomic) IBOutlet UIImageView *rapaidImageView;

@property (nonatomic, strong) NSMutableArray *articleArr;

/** 往期回答有更新 */
@property (nonatomic, assign) BOOL QAListHasNew;

@property (nonatomic, strong) NSMutableArray *synchronousTutorialArr;

@property (weak, nonatomic) IBOutlet UIView *redView;

@end

@implementation BIZHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupConfig];
    
    [self setupTableView];
    [self setupCycleScrollView];
    
//    //  轮播图
//    [self requestCycleScrollViewImageURLStringsWithType:@"0"];
//    
//    //  直播预告图
//    [self requestCycleScrollViewImageURLStringsWithType:@"2"];

//    //  直播间详情
//    [self requestLiveRoomDetailInfo];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.cycleScrollView adjustWhenControllerViewWillAppera];
    
    [self loadSynchronousTutorialListData];
    [self loadArticlesArrData];

    // MARK:轮播,直播预告图、直播房间信息为空时,再次请求
    self.cycleScrollViewImgesList.count ?: [self requestCycleScrollViewImageURLStringsWithType:@"0"];
    self.cclivePredictionImgesModel ?: [self requestCycleScrollViewImageURLStringsWithType:@"2"];
    [self requestLiveRoomDetailInfo];
    [self getTabBarRedBadgeData];
    
    // 版本更新
//    [self showALL];
    [[ReleaseConfirm DefultInstance] confirm];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}

//// 更新
//- (void)showALL
//{
//    ReleaseConfirm *defaultConfirm = [ReleaseConfirm DefultInstance];
//    if (defaultConfirm.isShowUpdate) {
//        [defaultConfirm showUpdateAlert];
//    }
//}

- (void)getTabBarRedBadgeData
{
    if (![BIZUserModel shareUser].login) {
        return;
    }
    
    [RequestTool POST:kTabBarRedBadgeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"kTabBarRedStatusURL---responseObject %@", responseObject);
         [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 1) {
            
            id tempMaxDate = responseObject[@"data"][@"maxDate"];
            BOOL isEmpty = [tempMaxDate isKindOfClass:[NSNull class]] || [tempMaxDate isEqual:[NSNull class]] || !tempMaxDate;
            if (!isEmpty) {
                NSNumber *maxDate = responseObject[@"data"][@"maxDate"];
                NSNumber *localDate = [BIZFileManager readUserDataForKey:@"atime"];
                if (maxDate && localDate.longLongValue) {
                    _QAListHasNew = localDate.longLongValue < maxDate.longLongValue? YES : NO;
                    [self.tableView reloadData];
                }
                
            }
            
            
            if (([responseObject[@"data"][@"oneRed"] integerValue])
                ||([responseObject[@"data"][@"rapidRed"]  integerValue])) {
                [self.tabBarController.tabBar.items[0] showBadge];
                
            } else {
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
            
            
            if ([responseObject[@"data"][@"officialCount"] integerValue]){
                self.redView.hidden = NO;
            } else {
                self.redView.hidden = YES;
            }
        
            
            if (([responseObject[@"data"][@"rapidRed"]  integerValue])) {
                self.repaidRedView.hidden = NO;
            } else {
                self.repaidRedView.hidden = YES;
            }
        }
        else {
//            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
         [MBProgressHUD hideHUD];
//        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//            [MBProgressHUD showErrorMessage:@"网络不给力"];
//        }
//        else {
//            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
//        }
    }];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    if (self.searchBar.searchBarTextField.isFirstResponder) {
        [self.searchBar.searchBarTextField resignFirstResponder];
    }
    
}

- (void)setupConfig {
    
    self.cycleScrollViewImgesList = [[NSMutableArray alloc] initWithCapacity:10];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (self.synchronousTutorialArr.count>=3) {
            return 3;
        }
        
        return self.synchronousTutorialArr.count;
        
    } else if (section == 2) {
        if (self.articleArr.count <= 3) {
            return self.articleArr.count;
        } else {
            return 3;
        }
    }
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        BIZSynchronousTutorialHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZSynchronousTutorialHomeCell" forIndexPath:indexPath];
        BIZSynchronousTutorialModel *model = self.synchronousTutorialArr[indexPath.row];
        cell.synchronousTutorialModel = model;
        
        MPWeakSelf(self);
        cell.sychronousAnalysisVideoDetailBlock = ^(){
            DeLog(@"解析");
            BIZSynchronousTutorialVideoDetailVC *playHomeVC = [[BIZSynchronousTutorialVideoDetailVC alloc]initWithUuid:model.videoId];
            playHomeVC.synchronousTutorialModel = model;
            [weakself.navigationController pushViewController:playHomeVC animated:YES];
        };
        
        return cell;
    }
    
    
    if (indexPath.section == 2) {
        BIZArticleListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZArticleListCell" forIndexPath:indexPath];
        cell.articleModel = self.articleArr[indexPath.row];
        cell.hiddenTopShadowView = YES;
        return cell;
    }
    
    MJWeakSelf;
    BIZHomeLiveStreamingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZHomeLiveStreamingCell" forIndexPath:indexPath];
    BIZCycleScrollViewImagesDataModel *dataM = self.cclivePredictionImgesModel.data.firstObject;
    cell.hasNew = _QAListHasNew;
    cell.liveRoomInfoDataM = self.liveRoomInfoDataM;
    cell.livePredictDataM = dataM;
    cell.clickSecondImgBlock = ^ {
        [weakSelf pushToLPredictWebVC];
    };
    cell.pushToQAListBlock = ^ {
        [weakSelf pushToQAListVC];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 52;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    BIZHomeSectionHeaderView *headerSectionView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"BIZHomeSectionHeaderView"];
    
    switch (section) {
        case 0:{
            headerSectionView.frontImageView.image = [UIImage imageNamed:@"同步辅导副本"];
            headerSectionView.titleLabel.text = @"最新财税政策同步辅导";
           
            [headerSectionView.rightBtn setImage:[UIImage imageNamed:@"形状1-1"] forState:UIControlStateNormal];
            [headerSectionView.rightBtn setTitle:@"更多" forState:UIControlStateNormal];
             [headerSectionView.rightBtn setButtonImageTitleStyle:ButtonImageTitleStyleRight padding:4];
//            [headerSectionView.rightBtn addTarget:self action:@selector(moreNewestFinancePolicyTutorialBtnClick) forControlEvents:UIControlEventTouchUpInside];
            
            MPWeakSelf(self);
            headerSectionView.rigthtBtnClickBlock = ^(){
                BIZSynchronousTutorialListVC *vc = [BIZSynchronousTutorialListVC viewControllerFromStoryboard];
                [weakself.navigationController pushViewController:vc animated:YES];
            };
            break;
        }
            
        case 1:{
            headerSectionView.frontImageView.image = [UIImage imageNamed:@"直播间副本"];
            headerSectionView.titleLabel.text = @"直播间";
          
            [headerSectionView.rightBtn setImage:[UIImage imageNamed:@"形状13"] forState:UIControlStateNormal];
            [headerSectionView.rightBtn setTitle:@"往期回顾" forState:UIControlStateNormal];
              [headerSectionView.rightBtn setButtonImageTitleStyle:ButtonImageTitleStyleLeft padding:4];
            MPWeakSelf(self);
            headerSectionView.rigthtBtnClickBlock = ^(){
                BIZLivePlayBackVC *playBackVC = [[BIZLivePlayBackVC alloc] init];
                playBackVC.playMode = NO;
                [weakself.navigationController pushViewController:playBackVC animated:YES];
            };
            break;
        }
    
        default:{
            headerSectionView.frontImageView.image = [UIImage imageNamed:@"热文推荐副本"];
            headerSectionView.titleLabel.text = @"热文推荐";
            [headerSectionView.rightBtn setImage:[UIImage imageNamed:@"形状1-1"] forState:UIControlStateNormal];
            [headerSectionView.rightBtn setTitle:@"更多" forState:UIControlStateNormal];
             [headerSectionView.rightBtn setButtonImageTitleStyle:ButtonImageTitleStyleRight padding:4];
            MPWeakSelf(self);
            headerSectionView.rigthtBtnClickBlock = ^(){
//                BIZFinanceTaxCircleVC *vc = [BIZFinanceTaxCircleVC viewControllerFromStoryboard];
//                vc.hiddenTabBar = YES;
//                [weakself.navigationController pushViewController:vc animated:YES];
                [weakself.tabBarController setSelectedIndex:2];
            };
            
            break;
        }

    }
    
    return headerSectionView;
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (self.searchBar.searchBarTextField.isFirstResponder) {
        [self.searchBar.searchBarTextField resignFirstResponder];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        BIZArticleDetailVC *detailVC = [BIZArticleDetailVC viewControllerFromStoryboard];
        BIZArticleModel *model;
        if (self.articleArr.count >= indexPath.row) {
            model = self.articleArr[indexPath.row];
        }
        detailVC.articleModel = model;
        MPWeakSelf(self);
        detailVC.commentSuccessReturnBlcok = ^() {
            model.discussNum = model.discussNum + 1;
              [weakself.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        };
        [self.navigationController pushViewController:detailVC animated:YES];
        
    } else if (indexPath.section == 0) {
        BIZSynchronousTutorialWordDetailVC *vc = [[BIZSynchronousTutorialWordDetailVC alloc]init];
        vc.synchronousTutorialModel = self.synchronousTutorialArr[indexPath.row];
        vc.detailType = BIZSynchronousTutorialWordDetailTypeSynchronous;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)setupNavBar {

    float padding = ((App_Frame_Width <= 320) ? 0.5 : 10);
    
    float labelWidth = [NSString widthForString:@"北京" fontSize:16 andHeight:44];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, labelWidth, 44)];
    label.textColor = [UIColor whiteColor];
    label.text = @"北京";
    label.font = SYSTEMFONT(16);
    UIBarButtonItem *labelItem = [[UIBarButtonItem alloc]initWithCustomView:label];
    
    UIView *leftSpace = [[UIView alloc]initWithFrame:CGRectMake(0, 0, padding, 44)];
    UIBarButtonItem *leftSpaceItem = [[UIBarButtonItem alloc]initWithCustomView:leftSpace];
    
    self.navigationItem.leftBarButtonItems = @[labelItem, leftSpaceItem];
    self.title = @"首页";

//    UIButton *messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    messageBtn.frame = CGRectMake(0, 0, 21, 44);
//    [messageBtn setImage:[UIImage imageNamed:@"组1"] forState:UIControlStateNormal];
//    [messageBtn addTarget:self action:@selector(messageBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *messageBtnItem = [[UIBarButtonItem alloc]initWithCustomView:messageBtn];
//    
//    UIView *rightSpace = [[UIView alloc]initWithFrame:CGRectMake(0, 0, padding, 44)];
//    UIBarButtonItem *rightSpaceItem = [[UIBarButtonItem alloc]initWithCustomView:rightSpace];
//    
//    self.navigationItem.rightBarButtonItems = @[messageBtnItem, rightSpaceItem];
//    
//    self.navigationItem.titleView = self.searchBar;
    
}


- (void)setupTableView
{
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 200;
    [self.tableView  setSeparatorColor:COLOR_UNLINE_GREY];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BIZBussinessPremissCell class]) bundle:nil] forCellReuseIdentifier:@"BIZBussinessPremissCell"];
     [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BIZArticleListCell class]) bundle:nil] forCellReuseIdentifier:@"BIZArticleListCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BIZHomeSectionHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"BIZHomeSectionHeaderView"];
    
//    NSArray *nibArr = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([BIZSynchronousTutorialHomeCell class]) owner:nil options:nil];
//    DeLog(@"对象数组：%@", nibArr);
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BIZSynchronousTutorialHomeCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([BIZSynchronousTutorialHomeCell class])];
    
}

- (void)setupCycleScrollView
{
    self.cycleScrollView.placeholderImage = [UIImage imageNamed:@"HomebackImage"];

    self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleToFill;
    self.cycleScrollView.currentPageDotColor = COLOR_NAVBAR_BLUE;
    self.cycleScrollView.clickItemOperationBlock = [self scrollViewClickItemBlock];

}

#pragma mark -- 网络请求

- (void)loadArticlesArrData {
    if (self.articleArr.count) {
        return;
    }
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    paramDic[@"type"] = @"label";
    paramDic[@"uuid"] = @"1";
    paramDic[@"pageIndex"] = @1;
    paramDic[@"pageEnd"] = @10;
    
    
    [MBProgressHUD showAnimationHUD];
    DeLog(@"paramDic%@",paramDic);
    [RequestTool POST:kArticleListUrl parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"文章responseObject:%@",responseObject);
//        [self stopRefresh];
        BIZArticleListModel *listModel = [BIZArticleListModel yy_modelWithJSON:responseObject];
        if (listModel.code == 1) {
            [MBProgressHUD hideHUD];
            
//            if (!listModel.articleArr.count) {
//                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
//                return ;
//            }
            
            [self.articleArr addObjectsFromArray:listModel.articleArr];
            [self.tableView reloadData];
        } else {
            [MBProgressHUD showErrorMessage:listModel.des];
            if (listModel.code == 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccessBlock = ^(){
                    [weakself loadArticlesArrData];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error:%@",error);
//        [self stopRefresh];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
        
    }];
}

- (void)stopRefresh{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}

/*
 type: 0 首页 1 直播
 
 */
- (void)requestCycleScrollViewImageURLStringsWithType:(NSString *)type {
    
//    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kCycleScrollViewImageGroupURL
           parameters:@{@"type":type?:@"0"}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  
                  BIZCycleScrollViewImagesModel *model = [BIZCycleScrollViewImagesModel yy_modelWithJSON:responseObject];
                   [MBProgressHUD hideHUD];
                  if (model.code.intValue == 1) {
                      [MBProgressHUD hideHUD];
                      
                      if (type.intValue == 0) {
                          self.cycleScrollViewImgesModel = model;
                          DeLog(@"轮播图数据response：%@", responseObject);

                          [model.data enumerateObjectsUsingBlock:^(BIZCycleScrollViewImagesDataModel *dataM, NSUInteger idx, BOOL * _Nonnull stop) {
                              NSString *urlStr = [NSString stringWithFormat:@"%@/%@/%@", kMainBaseUrl,kShowImage,dataM.image];
                              [self.cycleScrollViewImgesList addObject:urlStr];
                          }];
                          self.cycleScrollView.imageURLStringsGroup = self.cycleScrollViewImgesList;
                          
                      }else if (type.intValue == 2){
                          DeLog(@"直播预告图response：%@", responseObject);
                          self.cclivePredictionImgesModel = model;
                          
                          [self.tableView reloadData];
//                          if (model.data.count) {
//                              _livePredictImgStr = responseObject[@"data"][0];
//                              [self.tableView reloadData];
//                          }

                      }
                      
                  }else if (model.code.intValue == 2) {
                      
//                      [MBProgressHUD showErrorMessage:model.des];
                      BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                      
                      MJWeakSelf;
                      vc.loginSuccessBlock = ^(){
                          [weakSelf requestCycleScrollViewImageURLStringsWithType:@"0"];
                      };
                      [self presentViewController:vc animated:YES completion:nil];
                  }else {
                      
//                      [MBProgressHUD showErrorMessage:model.des];
                  }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"轮播图/直播预告图error：%@", error);
             [MBProgressHUD hideHUD];
//        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//            [MBProgressHUD showErrorMessage:@"网络不给力"];
//        }
//        else {
//            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
//        }
        
    }];
}

- (void)requestLiveRoomDetailInfo {
    MJWeakSelf;
//    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kLiveRoomDetailInfoURL
           parameters:nil
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  
                  DeLog(@"直播间详情response：%@", responseObject);
                  BIZLiveRoomDetailInfoModel *model = [BIZLiveRoomDetailInfoModel yy_modelWithJSON:responseObject];
                   [MBProgressHUD hideHUD];
                  if (model.code.intValue == 1) {
                     
                      weakSelf.liveRoomInfoDataM = model.data;
                      
                      [weakSelf.tableView reloadData];
                      
                  }else if (model.code.intValue == 2) {
                      
//                      [MBProgressHUD showErrorMessage:model.des];
                      BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                      
                      vc.loginSuccessBlock = ^(){
                          [weakSelf requestLiveRoomDetailInfo];
                      };
                      [weakSelf presentViewController:vc animated:YES completion:nil];
                  }else {
                      
//                      [MBProgressHUD showErrorMessage:model.des];
                  }
                  
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"直播间详情error：%@", error);
                   [MBProgressHUD hideHUD];
//                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//                      [MBProgressHUD showErrorMessage:@"网络不给力"];
//                      
//                  }else {
//                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
//                  }
                  
              }];
}



- (void)requestLivePayment {
    
    MJWeakSelf;
    [MBProgressHUD showActivityMessageInView:nil];
    [RequestTool POST:kLiveRoomPaymentURL
           parameters:nil
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"直播购买数据response：%@", responseObject);
                  NSString *code = responseObject[@"code"];
                  NSString *des  = responseObject[@"des"];
                  [MBProgressHUD hideHUD];
                  
                  if (code.intValue == 1 ) {
                      NSString *roomId = responseObject[@"data"][@"roomid"];
                      // type 参数。 0 无限次数直接成功  1提示是否购买
                      NSString *type = responseObject[@"data"][@"type"];

                      if (type.intValue == 0) {
                           [weakSelf loadLiveRoomWithRoomId:roomId];
                          
                      } else if (type.intValue ==1) {
                          [UIAlertController showAlertViewWithController:self
                                                                   title:@"提示"
                                                                 message:@"是否购买本次直播？"
                                                       cancelButtonTitle:@"否"
                                                      confirmButtonTitle:@"是"
                                                             cancelBlock:^{
                                                                 [MBProgressHUD hideHUD];
                                                             }
                                                            confirmBlock:^{
                                                                [weakSelf loadLiveRoomWithRoomId:roomId];
                                                            }];
                      }
                     
                      
                  } else if (code.intValue == 2) {
                      
                      [MBProgressHUD showErrorMessage:des];
                      BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                      
                      MJWeakSelf;
                      vc.loginSuccessBlock = ^(){
                          [weakSelf requestLivePayment];
                      };
                      [weakSelf presentViewController:vc animated:YES completion:nil];
                  }else {
                      
                      [MBProgressHUD showErrorMessage:des];
                  }
                  
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"轮播图数据error：%@", error);
                   [MBProgressHUD hideHUD];
              }];
}

#pragma mark -- 线下咨询

- (IBAction)offLineConsultButtonClick:(UIButton *)sender {
    BIZOfflineConsultRecordsVC *offlineVC = [[BIZOfflineConsultRecordsVC alloc] init];
    
    [self.navigationController pushViewController:offlineVC animated:YES];
}

#pragma mark -- 合同审核


//- (IBAction)checkContractButtonClick:(UIButton *)sender {
//    BIZContractVC *vc = [BIZContractVC viewControllerFromStoryboard];
//    [self.navigationController pushViewController:vc animated:YES];
//}
//
//#pragma mark --- 一对一咨询
//
//- (IBAction)oneToOneConsultBtnClick:(UIButton *)sender
//{
//    BIZConsultorListViewController *consultor = [[BIZConsultorListViewController alloc] initWithType:BIZConsultorListViewControllerTypeFromHome];
////    consultor.type = BIZConsultorListViewControllerTypeFromHome;
//    
//    [self.navigationController pushViewController:consultor animated:YES];
//}

#pragma - 往期回顾
- (void)historyBtnClick {
    BIZLivePlayBackVC *playBackVC = [[BIZLivePlayBackVC alloc] init];
    playBackVC.playMode = NO;
    
    [self.navigationController pushViewController:playBackVC animated:YES];
}

#pragma mark --- 点播入口
/** 简要描述
 * 详细描述
 */
- (IBAction)onlineClassBtnClick:(UIButton *)sender {
    
    BIZDWPlayerViewController *playerVC = [[BIZDWPlayerViewController alloc] init];
    [self.navigationController pushViewController:playerVC animated:YES];
    
}


- (IBAction)tapView:(UITapGestureRecognizer *)sender {
//    [self.view endEditing:YES];
    if (self.searchBar.searchBarTextField.isFirstResponder) {
        [self.searchBar.searchBarTextField resignFirstResponder];
    }
}


#pragma mark - UISearchBar Delegate

//已经开始编辑时的回调
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
//    BIZCustomSearchBar *sear = (BIZCustomSearchBar *)searchBar;
//    //取消按钮
//    sear.cancleButton.backgroundColor = [UIColor clearColor];
//    [sear.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
//    [sear.cancleButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
//    sear.cancleButton.titleLabel.font = [UIFont systemFontOfSize:14];
}

//编辑文字改变的回调
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//    NSLog(@"searchText:%@",searchText);
}

//搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    if (self.searchBar.searchBarTextField.isFirstResponder) {
        [self.searchBar.searchBarTextField resignFirstResponder];
    }
}

//取消按钮点击的回调
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    [self.view endEditing:YES];
}


-(BIZCustomSearchBar *)searchBar
{
    if (!_searchBar) {
        //加上 搜索栏
        _searchBar = [[BIZCustomSearchBar alloc] initWithFrame:CGRectMake(0, 5, App_Frame_Width, 30)];
        _searchBar.backgroundColor = [UIColor clearColor];
        _searchBar.delegate = self;
        //输入框提示
        _searchBar.placeholder = @"搜索文章、事务所、咨询师";
        //光标颜色
        _searchBar.cursorColor = [UIColor blueColor];
        //TextField
        _searchBar.searchBarTextField.layer.cornerRadius = 10;
        _searchBar.searchBarTextField.layer.masksToBounds = YES;
        _searchBar.searchBarTextField.layer.borderColor = [UIColor whiteColor].CGColor;
        _searchBar.searchBarTextField.layer.borderWidth = 1.0;
        
        //清除按钮图标
        _searchBar.clearButtonImage = [UIImage imageNamed:@"demand_delete"];
        
        //去掉取消按钮灰色背景
        _searchBar.hideSearchBarBackgroundImage = YES;
        
    }
    
    return _searchBar;
}

- (void)pushToLPredictWebVC {
    
    if (!self.cclivePredictionImgesModel.data.count) {
        [MBProgressHUD showTipMessageInView:@"预告信息待更新!"];
        return;
    }
    
    BIZCycleScrollViewImagesDataModel *dataM = self.cclivePredictionImgesModel.data.firstObject;
    BIZRemoteNotificationWebVC *webVC = [[BIZRemoteNotificationWebVC alloc] initWithWebContentId:dataM.imageId];
    webVC.navigationItem.title = dataM.title;
    [self.navigationController pushViewController:webVC animated:YES];
    
}

- (void)pushToQAListVC {
    // MARK:TO DO 往期回答列表
    BIZLiveHistoryAnswerVC *vc = [BIZLiveHistoryAnswerVC viewControllerFromStoryboard];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- 直播间入口
- (IBAction)clickImagePushToLiveRoom:(id)sender {
    if (self.liveRoomInfoDataM.status == 0) {
        [MBProgressHUD showTipMessageInView:@"直播未开始,请稍等" timer:4.0f];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self requestLiveRoomDetailInfo];
        });

        return;
    }
    // 直播扣费
    [self requestLivePayment];
    
}

- (void) loadLiveRoomWithRoomId:(NSString *)roomId {
    if (!roomId || [roomId isEqualToString:@""]) {
        [MBProgressHUD showErrorMessage:@"房间未创建,请先创建直播间!"];
        return;
    }

    NSString *userUUID = [BIZUserModel shareUser].detailModel.uuid;
    BIZPlayForPCVC *liveRoomVC = [[BIZPlayForPCVC alloc] initWithUserId:kCCDWPlayUserID
                                                                 RoomId:roomId
                                                             ViewerName:userUUID
                                                            ViewerToken:nil
                                                               roomName:_liveRoomInfoDataM.name];
    
    [self.navigationController pushViewController:liveRoomVC animated:YES];

}
#pragma mark -- private methods

//  scrollView点击block 回调
- (SDScrollViewClickItemOperationBlock)scrollViewClickItemBlock {
    SDScrollViewClickItemOperationBlock block ;
    __weak BIZHomePageViewController *weakSelf = self;
    block = ^(NSInteger currentIndex) {
        if (currentIndex >= weakSelf.cycleScrollViewImgesModel.data.count) {
            [MBProgressHUD showTipMessageInView:@"取值超出范围!!"];
            return ;
        }
        BIZCycleScrollViewImagesDataModel *dataM = weakSelf.cycleScrollViewImgesModel.data[currentIndex];
        DeLog(@"title-%@,content-%@",dataM.title,dataM.content);

        if (dataM.isNative.intValue == 0) {// 跳转原生界面
            // 预留接口
            BIZRemoteNotificationWebVC *webVC = [[BIZRemoteNotificationWebVC alloc] initWithWebContentId:dataM.imageId];
            webVC.navigationItem.title = dataM.title;

            [weakSelf.navigationController pushViewController:webVC animated:YES];

        }else if (dataM.isNative.intValue == 1){ // 跳转网页
            BIZRemoteNotificationWebVC *webVC = [[BIZRemoteNotificationWebVC alloc] initWithWebContentId:dataM.imageId];
            webVC.navigationItem.title = dataM.title;

            [weakSelf.navigationController pushViewController:webVC animated:YES];
            
        }
    };
    return block;
}


- (IBAction)consultTap:(UITapGestureRecognizer *)sender {
    if ((sender.view.tag -2000)==1) {
        BIZConsultViewController *vc = [BIZConsultViewController viewControllerFromStoryboard];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        BIZConsultorListViewController *consultor = [[BIZConsultorListViewController alloc] initWithType:BIZConsultorListViewControllerTypeFromHome];
        [self.navigationController pushViewController:consultor animated:YES];
    }
    
}

#pragma - 点击热点问题跳转
- (IBAction)hotIssueTap:(UITapGestureRecognizer *)sender {
    BIZHotTopicsHomeVC *hotTopicVC = [[BIZHotTopicsHomeVC alloc] init];
    
    [self.navigationController pushViewController:hotTopicVC animated:YES];
}

#pragma - 点击快速咨询跳转
- (IBAction)repaidConsultTap:(UITapGestureRecognizer *)sender {
    BIZConsultEditViewController *vc = [[BIZConsultEditViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}



- (NSMutableArray *)articleArr {
    if (!_articleArr) {
        _articleArr = [NSMutableArray array];
    }
    
    return _articleArr;
}

- (void)loadSynchronousTutorialListData {
    if (self.synchronousTutorialArr.count) {
        return;
    }
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    paramDic[@"pageIndex"] = @1;
    paramDic[@"pageEnd"] = @3;
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kSynchronousTutorialListUrl parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"首页同步辅导列表》》》》》》》》》》：%@", responseObject);
        [MBProgressHUD hideHUD];
        BIZSynchronousTutorialListModel *model = [BIZSynchronousTutorialListModel yy_modelWithJSON:responseObject];
        if (model.code == 1) {
            [self.synchronousTutorialArr addObjectsFromArray:model.data];
            [self.tableView reloadData];
            
        } else {
            [MBProgressHUD showErrorMessage:model.des];
            if (model.code == 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccessBlock = ^(){
                    [weakself loadSynchronousTutorialListData];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"首页同步辅导列表错误》》》》》》》》》》：%@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
    
}

- (NSMutableArray *)synchronousTutorialArr {
    if (!_synchronousTutorialArr) {
        _synchronousTutorialArr = [NSMutableArray array];
    }
    
    return _synchronousTutorialArr;
}

@end
